package nsu.edu.zsq.service.impl.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import nsu.edu.zsq.bean.Teacher;
import nsu.edu.zsq.bean.TeacherExample;
import nsu.edu.zsq.bean.TeacherExample.Criteria;
import nsu.edu.zsq.common.RequestHolder;
import nsu.edu.zsq.dao.TeacherMapper;
import nsu.edu.zsq.exception.ParamException;
import nsu.edu.zsq.param.PageQuery;
import nsu.edu.zsq.service.sys.SysLogService;
import nsu.edu.zsq.service.sys.TeacherService;
import nsu.edu.zsq.util.BeanValidator;
import nsu.edu.zsq.util.ExcelUtil;
import nsu.edu.zsq.util.PasswordUtil;

/** 
* Description: 教师的service实现类<br>
*/
@Slf4j
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private SysLogService sysLogService;
    
    @Override
    public Teacher getTeacher(int teacherId) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(teacherId);
        return teacher;
    }

    @Override
    public PageInfo<Teacher> listTeacherWithPage(int orgId, PageQuery pageQuery) {
        // 所有的教师
        int allTeacher = 0;
        PageHelper.startPage(pageQuery.getPageNum(),pageQuery.getPageSize());
        TeacherExample example = new TeacherExample();
        Criteria createCriteria = example.createCriteria();
        // 获取所有没有删除的教师
        createCriteria.andIsDeleteEqualTo(0);
        // 根据排序号，降序
        example.setOrderByClause("sort desc");
        List<Teacher> listTeacher = null;
        if (allTeacher == orgId) {
            listTeacher = teacherMapper.selectByExample(example);
        } else {
            createCriteria.andOrgIdEqualTo(orgId);
            listTeacher = teacherMapper.selectByExample(example);
        }
        PageInfo<Teacher> pageInfo = new PageInfo<Teacher>(listTeacher, pageQuery.getNavigatePages());
        return pageInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importTeacherFromExcel(MultipartFile excelFile) {
        List<Teacher> listTeacher = ExcelUtil.importExcel(excelFile, 1, 1, Teacher.class);
        saveBatchTeacher(listTeacher);
        log.info("导入教师信息数据一共【{}】条",listTeacher.size());

    }

    @Override
    public void exportTeacherToExcel(HttpServletResponse response) {
        TeacherExample example = new TeacherExample();
        List<Teacher> listTeacher = teacherMapper.selectByExample(example);
        // 导出操作
        ExcelUtil.exportExcel(listTeacher,"教师信息","Sheet1",Teacher.class,"教师信息.xlsx",response);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatchTeacher(List<Teacher> teachers) {
        List<Map<String, String>> after = new ArrayList<Map<String, String>>();
        for (Teacher teacher : teachers) {
            BeanValidator.check(teacher);
            if (checkTeahcerNoExist(teacher.getTeacherNo())) {
                throw new ParamException("存在相同的教师编号");
            }
            Map<String, String> map = new HashMap<String, String>(2);
            map.put("teacherNo", teacher.getTeacherNo());
            map.put("teacherName", teacher.getTeacherName());
            after.add(map);
            // 默认密码为身份证后六位
            String password = teacher.getIdNumber().substring(teacher.getIdNumber().length() - 6);
            if (password.endsWith("X") || password.endsWith("x")) {
                password = password.replace('x', '0');
                password = password.replace('X', '0');
            }
            teacher.setPassword(PasswordUtil.md5(password));
			/*
			 * teacher.setOperator(RequestHolder.getCurrentSysUser().getAccount());
			 * teacher.setOperatorTime(new Date());
			 */
            teacherMapper.insertSelective(teacher);
        }
        
		/*
		 * // 添加日志 String instruction = "教师信息管理-批量导入";
		 * sysLogService.saveSysLogBySysUser(null, after, instruction);
		 */
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveTeacher(Teacher teacher) {
        // 数据校验
        BeanValidator.check(teacher);
        if (checkTeahcerNoExist(teacher.getTeacherNo())) {
            throw new ParamException("该教师编号已经存在");
        }
        // 默认密码为身份证后六位
        String password = teacher.getIdNumber().substring(teacher.getIdNumber().length() - 6);
        if (password.endsWith("X") || password.endsWith("x")) {
            password = password.replace('x', '0');
            password = password.replace('X', '0');
        }
        teacher.setPassword(PasswordUtil.md5(password));
		/*
		 * teacher.setOperator(RequestHolder.getCurrentSysUser().getAccount());
		 * teacher.setOperatorTime(new Date());
		 */
        teacherMapper.insertSelective(teacher);
        
		/*
		 * // 添加日志 String instruction = "教师信息管理-添加教师";
		 * sysLogService.saveSysLogBySysUser(null, teacher, instruction);
		 */

    }
    
    /**
     * 检查是否存在相同的教师编号
     * @param teacherNo 教师编号
     * @return boolean true：存在 false：不存在
     */
    private boolean checkTeahcerNoExist(String teacherNo) {
        TeacherExample example = new TeacherExample();
        example.createCriteria().andTeacherNoEqualTo(teacherNo);
        return teacherMapper.countByExample(example) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatchTeacher(int[] teacherIds) {
        List<Teacher> before = new ArrayList<Teacher>();
        for (int teacherId : teacherIds) {
            Teacher beforeTeacher = getTeacher(teacherId);
            before.add(beforeTeacher);
            // TODO 删除教师信息的同时，删除教师关联的教授课程
            Teacher teacher = new Teacher();
            teacher.setId(teacherId);
            teacher.setIsDelete(1);
            teacherMapper.updateByPrimaryKeySelective(teacher);
        }

		/*
		 * // 添加日志 String instruction = "教师信息管理-批量删除";
		 * sysLogService.saveSysLogBySysUser(before, null, instruction);
		 */
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTeacher(int teacherId) {
        Teacher before = getTeacher(teacherId);
        // TODO 删除教师信息的同时，删除教师关联的教授课程
        Teacher teacher = new Teacher();
        teacher.setId(teacherId);
        teacher.setIsDelete(1);
        teacherMapper.updateByPrimaryKeySelective(teacher);
        
		/*
		 * // 添加日志 String instruction = "教师信息管理-单个删除";
		 * sysLogService.saveSysLogBySysUser(before, null, instruction);
		 */
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateTeacher(Teacher teacher) {
        // 数据校验
        BeanValidator.check(teacher);
        Teacher before = getTeacher(teacher.getId());
        if (!before.getTeacherNo().equals(teacher.getTeacherNo()) && checkTeahcerNoExist(teacher.getTeacherNo())) {
            throw new ParamException("该教师编号已经存在");
        }
		/*
		 * teacher.setOperator(RequestHolder.getCurrentSysUser().getAccount());
		 * teacher.setOperatorTime(new Date());
		 */
        teacherMapper.updateByPrimaryKeySelective(teacher);
        
		/*
		 * // 添加日志 String instruction = "教师信息管理-编辑教师";
		 * sysLogService.saveSysLogBySysUser(before, teacher, instruction);
		 */
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void resetPassword(int teacherId) {
        Teacher beforeTeacher = getTeacher(teacherId);
        // 默认密码为身份证后六位
        String password = beforeTeacher.getIdNumber().substring(beforeTeacher.getIdNumber().length() - 6);
        if (password.endsWith("X") || password.endsWith("x")) {
            password = password.replace('x', '0');
            password = password.replace('X', '0');
        }
        Teacher before = Teacher.builder().id(beforeTeacher.getId()).teacherNo(beforeTeacher.getTeacherNo())
                .password(beforeTeacher.getPassword()).operator(beforeTeacher.getOperator())
                .operatorTime(beforeTeacher.getOperatorTime()).build();
        Teacher after = Teacher.builder().id(beforeTeacher.getId()).teacherNo(beforeTeacher.getTeacherNo())
                .password(PasswordUtil.md5(password)).operator(RequestHolder.getCurrentSysUser().getAccount())
                .operatorTime(new Date()).build();
        teacherMapper.updateByPrimaryKeySelective(after);
		/*
		 * // 添加日志 String instruction = "教师信息管理-重置密码";
		 * sysLogService.saveSysLogBySysUser(before, after, instruction);
		 */
    }

}
